package com.fcy.teamwork.business.main.homepage

import android.content.res.Resources.getSystem
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.fcy.teamwork.base.fromJson
import com.fcy.teamwork.base.toast
import com.fcy.teamwork.business.main.homepage.viewmodel.TaskMarketService
import com.fcy.teamwork.databinding.TaskInfoDialogBinding
import com.fcy.teamwork.pojo.JobDetail
import com.fcy.teamwork.repo.RetrofitClient
import kotlinx.coroutines.launch

class TaskInfoFrag : DialogFragment() {
    private lateinit var data: JobDetail
    private lateinit var binding: TaskInfoDialogBinding
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = TaskInfoDialogBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        getSystem().displayMetrics.apply {
            dialog?.window?.setLayout(widthPixels / 6 * 5, heightPixels / 3 * 2)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        processArgsWithUI()
        binding.actionBar.apply {
            ibBack.setOnClickListener {
                closeSelf()
            }
            tvTitle.text = data.projectInfo.name
        }
        binding.btnApply.setOnClickListener {
            // 防止重复多次点击
            it.isClickable = false
            newApply(it)
        }
        binding.tvContent.text = data.projectInfo.description
    }

    private fun newApply(btn: View) {
        lifecycleScope.launch {
            val res = RetrofitClient.getService<TaskMarketService>().applyJob(data.job)
            context?.toast(if (res.message.isNullOrBlank()) "请求失败，请稍后重试" else res.message)
            btn.isClickable = true
            closeSelf()
        }
    }

    private fun processArgsWithUI() {
        if (arguments?.getBoolean("canApply") != true)
            binding.btnApply.visibility = View.INVISIBLE
        data = arguments?.getString("jobDetail")?.fromJson()
            ?: throw IllegalArgumentException("项目信息没有成功获取")
    }

    private fun closeSelf() {
        parentFragmentManager.beginTransaction().remove(this).commit()
    }
}